<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计算年龄</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
      }

      .container {
        text-align: center;
      }

      form {
        margin-bottom: 20px;
      }

      .result {
        margin-top: 20px;
        font-size: 18px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h2>计算年龄</h2>

      <label for="dob">请输入您的出生年月（格式：YYYY-MM-DD）：</label><br />

      <span>年：</span>
      <input type="text" required />
      <br />

      <span>月：</span>
      <input type="text" required /><br />

      <span>日：</span>
      <input type="text" required />
      <br />

      <button id="btn">计算年龄</button>

      <div id="ageResult" class="result"></div>
    </div>
    <script>
      document.getElementById("btn").addEventListener("click", () => {
        // 获取输入的年月日input里的值
        var year = document.querySelectorAll("input")[0].value;
        var month = document.querySelectorAll("input")[1].value;
        var day = document.querySelectorAll("input")[2].value;
        // 拼接成字符串
        var allday = year + month + day;
        // 用获取当前的月份减掉输入的月份
        var chaMonth = new Date().getMonth() - month;
        // 用获取当前的年份减掉输入的月份
        var age = new Date().getFullYear() - year;
        // 当前的月份减掉输入的月份小于0并且当前的日期小于输入的日期式 岁数减1
        if (chaMonth < 0 || (chaMonth == 0 && new Date().getDate() < day)) {
          age--;
        }
        const ageResult = document.getElementById("ageResult");
        ageResult.textContent = `您的年龄为 ${age} 岁`;
      });
    </script>
  </body>
</html>
